function writeCMD(model,L,nmCMD,appn)
%% writes a command file named nmCMD using the 'model' and the structure L read from a CSV file or created in other ways
if appn=='a'
    fid=fopen(nmCMD,'a');
else
    fid=fopen(nmCMD,'w');
end

if ~(isempty(model))
    % typical initial matters
    fprintf(fid,'SPECIAL>NOINTERACTION|1\r\n');
    fprintf(fid,['SPECIAL>LOADMODEL|' model '\r\n']);

end
% waste some time to avoid errors
    fprintf(fid,'MENU>VDF2TAB|waste|waste||\r\n');
%input commands from the control structure
fnames=fieldnames(L);

for i=1:numel(fnames)
    field=L.(fnames{i});
    if ~(isempty(field))
        rnname='!';
        switch fnames{i}
            
            
            case {'payoff','sensitivity', 'optparm', 'savelist', 'senssavelist'}
                for j=1:numel(field)
                    fprintf(fid,['SIMULATE>' fnames{i} '|' field{j} '\r\n']);
                end
            case 'data'
                for j=1:numel(field)
                    fprintf(fid,['SIMULATE>DATA|' field{j} '\r\n']);
                end
            case 'changes'
                for j=1:numel(field)
                    if j==1
                        fprintf(fid,['SIMULATE>READCIN|' field{j} '\r\n']);
                    else
                        fprintf(fid,['SIMULATE>ADDCIN|' field{j} '\r\n']);
                    end
                end
            case 'runname'
                fprintf(fid,['SIMULATE>RUNNAME|' field{1} '|O\r\n']);
                rnname=field{1};
            case 'setvals'
                for j=1:numel(field)
                    fprintf(fid,['SIMULATE>SETVAL|' field{j} '\r\n']);
                end
            case 'runtype'
                switch lower(field{1})
                    case 'run'
                        fprintf(fid,'MENU>RUN|O\r\n');
                    case 'optimize'
                        fprintf(fid,'MENU>RUN_OPTIMIZE|O\r\n');
                    case 'sensitivity'
                        fprintf(fid,'MENU>RUN_SENSITIVITY|O\r\n');
                end
                
            case 'export'
                fprintf(fid,['MENU>VDF2TAB|' rnname '|' rnname '|' field{1} '|' field{2} '\r\n']);
                
        end
    end
end


% enter ending commands



if L.exit
    fprintf(fid,'SPECIAL>CLEARRUNS\r\n\r\n');
    fprintf(fid,'MENU>EXIT\r\n');

end
fclose(fid);
end
